#include <iostream>
#include <stdlib.h>
#include <cerrno>
#include <cstring>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
void Usage(std::string s){
    std::cout << "Usage :" << "\n\t" << s << " server_ip server_port " << std::endl;
}
int main(int argc, char* argv[]){
    if (argc != 3){
        Usage(argv[0]);
        return 1;
    }
    std::string svr_ip = argv[1];
    uint16_t svr_port = atoi(argv[2]);
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0){
        std::cerr << "socket errno" << errno << std::endl;
        return 2;
    } 

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_addr.s_addr = inet_addr(svr_ip.c_str());
    server.sin_family = AF_INET;
    server.sin_port = htons(svr_port);
    if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0){
        std::cerr << "connect errno" << errno << std::endl;
        return 3;
    }

    //进行正常的业务请求
    while (true){
        std::cout << "Please Enter# ";
        char buffer[1024];
        fgets(buffer, sizeof(buffer) - 1, stdin);
        write(sock, buffer, strlen(buffer));

        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0){
            buffer[s] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
}